package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.service.LoginService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {
    /**
     * 登录功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO dto) {

        //校验参数
        if (StringUtils.isBlank(dto.getName()) ||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数错误");
        }
        //根据用户名查询用户信息
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AdUser::getName,dto.getName());
        AdUser adUser = this.getOne(wrapper);
        if (adUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码错误");
        }
        //判断状态是否有效
        if (9!=adUser.getStatus()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常，请联系管理员");
        }
        //获取数据库密码和盐，匹配密码
        String password = adUser.getPassword(); //数据库密码 已加密
        String salt = adUser.getSalt();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes()); //输入的密码进行加盐加密
        if (!password.equalsIgnoreCase(inputPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或密码错误");
        }
        //修改最近登陆时间
        adUser.setLoginTime(new Date());
        //保存到数据库
        this.updateById(adUser);

        //办法 token  jwt令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //返回结果
        AdUserVO userVO = new AdUserVO();
        //将部分用户信息 拷贝到响应对象中
        BeanUtils.copyProperties(adUser,userVO);

        Map map=new HashMap<>();
        map.put("token",token);
        map.put("user",userVO);

        return ResponseResult.okResult(map);
    }
}
